from apps.util.LayDate import LayDate

from flask import render_template, Blueprint, request
from apps.pojo.Entitiy import User,UserSchema,db

user_bp = Blueprint("user",__name__,url_prefix='/user')
user_schema = UserSchema(many=True)
@user_bp.route("/tolist")
def tolist():
    return render_template("user/list.html")
@user_bp.route('list',methods=['GET','POST'])
def list():
    #接受分页参数 page当前页 limit 每页显示的条数
    page = request.args.get('page',1,type=int)
    limit = request.args.get('limit',10,type=int)

    #查询用户表数据
    count = User.query.count()

    #查询用户集合数据
    offset = (page-1)*limit
    userList = User.query.offset(offset).limit(limit).all()
    #将集合转换成json
    users = user_schema.dump(userList)
    #构造layui格式json对象""
    return {
        "code":0,
        "msg":"查询成功",
        "count":count,
        "data":users
    }


@user_bp.route("/toadd")
def toadd():
    return render_template("user/add.html")
@user_bp.route("/addSave",methods=['POST'])
def addSave():
    param = request.form
    user = User()
    user.username = param.get('username')
    user.password = param.get('password')
    user.sex = param.get('sex')
    try:
        #保存到数据库
        db.session.add(user)
        #提交事务
        db.session.commit()
        return LayDate.data2(200,'添加成功')
    except Exception as e:
        return LayDate.data2(500,'添加失败')
@user_bp.route('/toupdate/<int:id>')
def toUpdate(id):
    user = User.query.filter(User.id == id).first()
    return render_template('user/edit.html', user=user)

@user_bp.route("/updateSave",methods=['POST'])
def updateSave():
    param = request.form
    id = param.get('id')
    user = User.query.filter(User.id == id).first()
    user.username = param.get('username')
    user.password = param.get('password')
    # user.sex = param.get('sex')
    try:
        db.session.commit()
        return LayDate.data2(200, '修改成功')
    except Exception as e:
        db.session.rollback()
        return LayDate.data2(500, '修改失败')

@user_bp.route("/delete",methods=["POST"])
def delete():
    id = request.form.get('id')
    user = User.query.filter(User.id==id).first()
    try:
        db.session.remove(user)
        db.session.commit()
        return LayDate.data2(200,'删除成功')
    except Exception as e:
        db.session.rollback()
        return LayDate.data2(500,'删除失败')